package com.ibeeking.found.cop.b.rest.service.mq;

import com.ibeeking.found.cop.b.rest.service.IKfAccountService;
import com.ibeeking.found.cop.b.rest.service.IKfFriendsMessageService;
import com.ibeeking.found.cop.b.rest.service.IKfServicerService;
import com.ibeeking.found.cop.b.rest.service.IWxOpenService;
import com.ibeeking.found.cop.service.common.param.KfAccountParam;
import com.ibeeking.found.cop.service.common.param.KfFriendsMessageParam;
import com.ibeeking.found.cop.service.common.param.KfServicerParam;
import com.ibeeking.found.cop.service.common.param.MqSyncCopParam;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.log.utils.LogUtils;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.data.StringUtils;
import com.ibeeking.nematos.utils.date.DateUtil;
import com.ibeeking.nematos.utils.json.JsonUtils;
import me.chanjar.weixin.cp.api.WxCpKfService;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.kf.WxCpKfAccountListResp;
import me.chanjar.weixin.cp.bean.kf.WxCpKfMsgListResp;
import me.chanjar.weixin.cp.bean.kf.WxCpKfServicerListResp;
import me.chanjar.weixin.cp.config.impl.WxCpRedissonConfigImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CopKfMqConsumerHandler {

    @Resource
    private IKfAccountService kfAccountServiceServiceImpl;

    @Resource
    private IKfServicerService kfServicerServiceServiceImpl;

    @Resource
    private IKfFriendsMessageService kfFriendsMessageServiceServiceImpl;

    @Resource
    private IWxOpenService wxOpenServiceImpl;

    public boolean syncKfAccountFromWxcp(MqSyncCopParam mqParam, Map<String, Object> extMap) {
        try {
            Long tenantId = mqParam.getTenantId();
            WxCpService wxCpService = wxOpenServiceImpl.getWxCpService(tenantId);
            WxCpRedissonConfigImpl wxCpConfigStorage = (WxCpRedissonConfigImpl)wxCpService.getWxCpConfigStorage();
            if (wxCpConfigStorage == null) {
                throw new BusinessException("获取企微服务失败!");
            }
            wxCpConfigStorage.setCorpSecret("A5pyzWIcAe1wpvKs4R69JVhZeygB1TI8vnbc7g8BU90");
            String wxCpAccessToken = wxCpService.getAccessToken(true);
            wxCpConfigStorage.updateAccessToken(wxCpAccessToken, 7200);
            wxCpService.setWxCpConfigStorage(wxCpConfigStorage);
            LogUtils.info("====process wxCpConfigStorage:{}====", JsonUtils.toJsonStr(wxCpConfigStorage));
            String corpId = wxCpConfigStorage.getCorpId();
            LogUtils.info("====corpId:{}====",corpId);
            WxCpKfService wxCpKfService = wxCpService.getKfService();
            if (wxCpKfService == null) throw new BusinessException("获取客服服务出错!");

            WxCpKfAccountListResp wxCpKfAccountListResp = wxCpKfService.listAccount(0, 100);
            LogUtils.info("====process WxCpKfAccountListResp:{}====", JsonUtils.toJsonStr(wxCpKfAccountListResp));
            if(wxCpKfAccountListResp != null){
                List<KfAccountParam> kfAccountParamList = new ArrayList<>();
                List<WxCpKfAccountListResp.AccountListDTO> accountList = wxCpKfAccountListResp.getAccountList();
                if(Collections3.isNotEmpty(accountList)){
                    for(WxCpKfAccountListResp.AccountListDTO kfAccount:accountList){
                        KfAccountParam kfAccountParam = new KfAccountParam();
                        kfAccountParam.setOpenKfid(kfAccount.getOpenKfid());
                        kfAccountParam.setName(kfAccount.getName());
                        kfAccountParam.setAvatarUrl(kfAccount.getAvatar());
                        kfAccountParamList.add(kfAccountParam);
                    }
                }
                LogUtils.info("====process kfAccountParamList:{}====", JsonUtils.toJsonStr(kfAccountParamList));
                if(Collections3.isNotEmpty(kfAccountParamList)){
                    kfAccountServiceServiceImpl.saveOrUpdateOrDeleteBatchKfAccount(tenantId, kfAccountParamList);
                }
            }
            return true;
        } catch (Exception e) {
            LogUtils.error("同步客服账号任务处理异常:{}", e);
            return false;
        }
    }

    public boolean syncKfServicerFromWxcp(MqSyncCopParam mqParam, Map<String, Object> extMap) {
        try {
            Long tenantId = mqParam.getTenantId();
            Long kfAcountId = mqParam.getAccountId();
            String openkfId = mqParam.getOpenKfId();
            if(StringUtils.isEmpty(openkfId)) throw new BusinessException("参数openKfId为空!");
            WxCpService wxCpService = wxOpenServiceImpl.getWxCpService(tenantId);
            WxCpRedissonConfigImpl wxCpConfigStorage = (WxCpRedissonConfigImpl)wxCpService.getWxCpConfigStorage();
            if (wxCpConfigStorage == null) {
                throw new BusinessException("获取企微服务失败!");
            }
            wxCpConfigStorage.setCorpSecret("A5pyzWIcAe1wpvKs4R69JVhZeygB1TI8vnbc7g8BU90");
            String wxCpAccessToken = wxCpService.getAccessToken(true);
            wxCpConfigStorage.updateAccessToken(wxCpAccessToken, 7200);
            wxCpService.setWxCpConfigStorage(wxCpConfigStorage);
            LogUtils.info("====process wxCpConfigStorage:{}====", JsonUtils.toJsonStr(wxCpConfigStorage));
            String corpId = wxCpConfigStorage.getCorpId();
            LogUtils.info("====corpId:{}====",corpId);
            WxCpKfService wxCpKfService = wxCpService.getKfService();
            if (wxCpKfService == null) throw new BusinessException("获取客服服务出错!");


            WxCpKfServicerListResp wxCpKfServicerListResp = wxCpKfService.listServicer(openkfId);
            LogUtils.info("====process wxCpKfServicerListResp:{}====", JsonUtils.toJsonStr(wxCpKfServicerListResp));
            if(wxCpKfServicerListResp != null){
                List<KfServicerParam> kfServicerParamList = new ArrayList<>();
                List<WxCpKfServicerListResp.WxCpKfServicerStatus> wxCpKfServicerStatusList = wxCpKfServicerListResp.getServicerList();
                if(Collections3.isNotEmpty(wxCpKfServicerStatusList)){
                    for(WxCpKfServicerListResp.WxCpKfServicerStatus kfServicer:wxCpKfServicerStatusList){
                        KfServicerParam kfServicerParam = new KfServicerParam();
                        kfServicerParam.setOpenKfid(openkfId);
                        kfServicerParam.setEmployeeCode(kfServicer.getUserId());
                        kfServicerParam.setStatus(kfServicer.getStatus());
                        kfServicerParamList.add(kfServicerParam);
                    }
                }
                LogUtils.info("====process kfServicerParamList:{}====", JsonUtils.toJsonStr(kfServicerParamList));
                if(Collections3.isNotEmpty(kfServicerParamList)){
                    kfServicerServiceServiceImpl.saveOrUpdateOrDeleteBatchKfServicer(tenantId, kfAcountId, kfServicerParamList);
                }
            }
            return true;
        } catch (Exception e) {
            LogUtils.error("同步客服账号任务处理异常:{}", e);
            return false;
        }
    }

    public boolean syncKfFriendsMessageFromWxcp(MqSyncCopParam mqParam, Map<String, Object> extMap) {
        try {
            Long tenantId = mqParam.getTenantId();
            Long kfAcountId = mqParam.getAccountId();
            List<String> openkfIdList = mqParam.getOpenKfIds();
            if(Collections3.isEmpty(openkfIdList)) throw new BusinessException("参数openKfId为空!");
            WxCpService wxCpService = wxOpenServiceImpl.getWxCpService(tenantId);
            WxCpRedissonConfigImpl wxCpConfigStorage = (WxCpRedissonConfigImpl)wxCpService.getWxCpConfigStorage();
            if (wxCpConfigStorage == null) {
                throw new BusinessException("获取企微服务失败!");
            }
            wxCpConfigStorage.setCorpSecret("A5pyzWIcAe1wpvKs4R69JVhZeygB1TI8vnbc7g8BU90");
            String wxCpAccessToken = wxCpService.getAccessToken(true);
            wxCpConfigStorage.updateAccessToken(wxCpAccessToken, 7200);
            wxCpService.setWxCpConfigStorage(wxCpConfigStorage);

            String corpId = wxCpConfigStorage.getCorpId();

            WxCpKfService wxCpKfService = wxCpService.getKfService();
            if (wxCpKfService == null) throw new BusinessException("获取客服服务出错!");
            List<KfFriendsMessageParam> allKfFriendsMessageParamList = new ArrayList<>();
            for(String openkfId:openkfIdList) {
                String nextCursor = null;
                do {
                    WxCpKfMsgListResp wxCpKfMsgListResp = wxCpKfService.syncMsg(nextCursor, null, 800, 0, openkfId);
                    LogUtils.info("====process WxCpKfMsgListResp:{}====", JsonUtils.toJsonStr(wxCpKfMsgListResp));
                    if (wxCpKfMsgListResp != null) {
                        nextCursor = wxCpKfMsgListResp.getNextCursor();
                        List<WxCpKfMsgListResp.WxCpKfMsgItem> wxCpKfMsgItemList = wxCpKfMsgListResp.getMsgList();
                        if (Collections3.isNotEmpty(wxCpKfMsgItemList)) {
                            wxCpKfMsgItemList.stream().forEach(d -> {
                                KfFriendsMessageParam param = new KfFriendsMessageParam();
                                param.setOpenKfid(d.getOpenKfid());
                                param.setFriendsCode(d.getExternalUserId());
                                param.setEmployeeCode(d.getServicerUserId());
                                param.setMessageCode(d.getMsgId());
                                param.setMsgType(d.getMsgType());
                                param.setSourceFrom(d.getOrigin());
                                Long sendTimeL = d.getSendTime();
                                if (sendTimeL != null) {
                                    LocalDateTime sendTime = DateUtil.longToLocalDateTime(sendTimeL);
                                    param.setSendTime(DateUtil.localDateTimeToStr(sendTime));
                                }
                                allKfFriendsMessageParamList.add(param);
                            });
                        }
                    }
                } while (nextCursor == null);
            }
            if(Collections3.isNotEmpty(allKfFriendsMessageParamList)){
                kfFriendsMessageServiceServiceImpl.saveOrUpdateOrDeleteBatchKfFriendsMessage(tenantId, kfAcountId, allKfFriendsMessageParamList);
            }
            return true;
        } catch (Exception e) {
            LogUtils.error("同步客服互动消息任务处理异常:{}", e);
            return false;
        }
    }
}
